//
// Created by SX50821 on 25-6-26.
//
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

int main()
{
    //建立socket
    //返回文件描述符，-1表示无效
    //参数1：AP_INET使用ipv4  AP_INET6使用ipv6
    //参数2：SOCK_STREAM表示tcp   SOCK_DGRAM表示udp
    //参数3：参考注释
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd <= 0)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    //复用socket
    int opt = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));

    //地址信息
    struct sockaddr_in address;
    int addrelen = sizeof(address);
    //使用ip地址
    address.sin_family = AF_INET;
    //绑定任意地址  表示通过本机的所有ip都可以连接
    address.sin_addr.s_addr = INADDR_ANY;
    //htons 表示底层数据编码方式由小端改成大端
    address.sin_port = htons(9527);
    int bindResult = bind(server_fd, (struct sockaddr *) &address, sizeof(address));
    if (bindResult < 0)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    int listenResult = listen(server_fd, 5);
    if (listenResult < 0)
    {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }
    printf("Server listening on port 9527\n");
    fflush(stdout);

    for (;;)
    {
        //使用多线程处理每个不同的sockrt
        int *client_socket = (int *) malloc(sizeof(int));
        //返回客户端的socket
        *client_socket = accept(server_fd, (struct sockaddr *) &address, (socklen_t *) &addrelen);
        if (client_socket <0)
        {
            perror("accept failed");
            continue;
        }
        printf("Client connected\n");
        fflush(stdout);
        //创建多线程，处理不同的socket
        pthread_t t_id;
        pthread_create(&t_id, NULL, NULL, client_socket);
    }
    close(server_fd);
    return 0;
}




